package db;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.LogicalExpression;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.SimpleExpression;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 * A data access object (DAO) providing persistence and search support for
 * Receiveorder entities. Transaction control of the save(), update() and
 * delete() operations can directly support Spring container-managed
 * transactions or they can be augmented to handle user-managed Spring
 * transactions. Each of these methods provides additional information for how
 * to configure it for the desired type of transaction control.
 * 
 * @see db.Receiveorder
 * @author MyEclipse Persistence Tools
 */

public class ReceiveorderDAO extends HibernateDaoSupport {
	private static final Log log = LogFactory.getLog(ReceiveorderDAO.class);
	// property constants
	public static final String CODE = "code";
	public static final String SUPPLIER = "supplier";
	public static final String RECEIVE_COMPANY = "receiveCompany";
	public static final String TMP_CODE = "tmpCode";
	public static final String TOP_TYPE = "topType";
	public static final String SUB_STORE = "subStore";
	public static final String PRO_CODE = "proCode";
	public static final String REMARK = "remark";
	public static final String TEAM_ID = "teamId";
	public static final String RECEIVER_USER_ID = "receiverUserId";
	public static final String RCODE = "rcode";
	public static final String IS_DELETE = "isDelete";

	protected void initDao() {
		// do nothing
	}

	public void save(Receiveorder transientInstance) {
		log.debug("saving Receiveorder instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(Receiveorder persistentInstance) {
		log.debug("deleting Receiveorder instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public Receiveorder findById(java.lang.Integer id) {
		log.debug("getting Receiveorder instance with id: " + id);
		try {
			Receiveorder instance = (Receiveorder) getHibernateTemplate().get(
					"db.Receiveorder", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(Receiveorder instance) {
		log.debug("finding Receiveorder instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding Receiveorder instance with property: "
				+ propertyName + ", value: " + value);
		try {
			String queryString = "from Receiveorder as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByCode(Object code) {
		return findByProperty(CODE, code);
	}

	public List findBySupplier(Object supplier) {
		return findByProperty(SUPPLIER, supplier);
	}

	public List findByReceiveCompany(Object receiveCompany) {
		return findByProperty(RECEIVE_COMPANY, receiveCompany);
	}

	public List findByTmpCode(Object tmpCode) {
		return findByProperty(TMP_CODE, tmpCode);
	}

	public List findByTopType(Object topType) {
		return findByProperty(TOP_TYPE, topType);
	}

	public List findBySubStore(Object subStore) {
		return findByProperty(SUB_STORE, subStore);
	}

	public List findByProCode(Object proCode) {
		return findByProperty(PRO_CODE, proCode);
	}

	public List findByRemark(Object remark) {
		return findByProperty(REMARK, remark);
	}

	public List findByTeamId(Object teamId) {
		return findByProperty(TEAM_ID, teamId);
	}

	public List findByReceiverUserId(Object receiverUserId) {
		return findByProperty(RECEIVER_USER_ID, receiverUserId);
	}

	public List findByRcode(Object rcode) {
		return findByProperty(RCODE, rcode);
	}

	public List findByIsDelete(Object isDelete) {
		return findByProperty(IS_DELETE, isDelete);
	}

	public List findAll() {
		log.debug("finding all Receiveorder instances");
		try {
			String queryString = "from Receiveorder";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public Receiveorder merge(Receiveorder detachedInstance) {
		log.debug("merging Receiveorder instance");
		try {
			Receiveorder result = (Receiveorder) getHibernateTemplate().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(Receiveorder instance) {
		log.debug("attaching dirty Receiveorder instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(Receiveorder instance) {
		log.debug("attaching clean Receiveorder instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static ReceiveorderDAO getFromApplicationContext(
			ApplicationContext ctx) {
		return (ReceiveorderDAO) ctx.getBean("ReceiveorderDAO");
	}
	
	public Map getReceiveorder(int pageNo, int pageSize, String[][] order, List where, String[][] fields, String[] join) {
		ProjectionList pl = Projections.projectionList();	
		for (int i = 0; i < fields.length; i++) {
			String[] field = fields[i];
			if("group".equals(field[0])){
				pl.add(Projections.groupProperty(field[1]));
			}else{
				pl.add(Projections.property(field[1]));
			}
		}
		
		DetachedCriteria dc = DetachedCriteria.forClass(Receiveorder.class);
		if(join != null && join.length > 0)
		for(int i=0;i<join.length;i++){
			if("project".equals(join[i]))
				dc.createAlias("project", "p");
		}
		dc.setProjection(pl);

		if(order != null && order.length > 0)
		for(int i=0; i<order.length; i++){
			String[] temp = order[i];
			if ("desc".equals(order[i][0])) {
				dc.addOrder(Order.desc(order[i][1]));
			} else if ("asc".equals(order[i][1])) {
				dc.addOrder(Order.asc(order[i][1]));
			}
		}
		
		if(where != null && where.size() > 0)
		for(int i=0; i<where.size(); i++){
			Object[] w = (Object[])where.get(i);
			String condition = String.valueOf(w[0]);
			String filed = String.valueOf(w[1]);
			if("eq".equals(condition)){
				dc.add(Property.forName(filed).eq(w[2]));
			}else if("eqProperty".equals(condition)){
				dc.add(Property.forName(filed).eqProperty((String)w[2]));
			}else if("like".equals(condition)){
				dc.add(Property.forName(filed).like("%" + w[2] + "%"));
			}else if("ne".equals(condition)){
				dc.add(Property.forName(filed).ne(w[2]));
			}else if("neProperty".equals(condition)){
				dc.add(Property.forName(filed).neProperty((String)w[2]));
			}else if("or".equals(condition)){
				dc.add(handleOr((List)w[2]));
			}
		}
       
		int recordSize = getCount(where, join);
		
		List data = getHibernateTemplate().findByCriteria(dc,pageNo * pageSize, pageSize);
		
		int pageTotal = pageSize == 0 ? 1 : recordSize % pageSize == 0 ? recordSize / pageSize : recordSize / pageSize + 1;
		Map map = new HashMap();
		map.put("data", data);
		map.put("recordSize", recordSize);
		map.put("pageTotal", pageTotal);
		map.put("pageSize", pageSize);
		map.put("pageNo", pageNo);
		return map;
	}
	
	public int getCount(List where, String[] join){
		DetachedCriteria dc = DetachedCriteria.forClass(Receiveorder.class)
		.setProjection(Projections.rowCount());
		
		if(join != null && join.length > 0)
			for(int i=0;i<join.length;i++){
				if("project".equals(join[i]))
					dc.createAlias("project", "p");
			}
		
		if(where != null && where.size() > 0)
		for(int i=0;i<where.size();i++){
			Object[] w = (Object[])where.get(i);
			String condition = String.valueOf(w[0]);
			String filed = String.valueOf(w[1]);
			if("eq".equals(condition)){
				dc.add(Property.forName(filed).eq(w[2]));
			}else if("eqProperty".equals(condition)){
				dc.add(Property.forName(filed).eqProperty((String)w[2]));
			}else if("like".equals(condition)){
				dc.add(Property.forName(filed).like("%" + w[2] + "%"));
			}else if("ne".equals(condition)){
				dc.add(Property.forName(filed).ne(w[2]));
			}else if("neProperty".equals(condition)){
				dc.add(Property.forName(filed).neProperty((String)w[2]));
			}else if("or".equals(condition)){
				dc.add(handleOr((List)w[2]));
			}
		}
		
		return (Integer) getHibernateTemplate().findByCriteria(dc).get(0);
	}
	
	public LogicalExpression handleOr(List list){
		LogicalExpression le = null;
		SimpleExpression se = null;
		SimpleExpression se1 = null;
		SimpleExpression se2 = null;
		
		for(int i= list.size() - 1;i >= 0;i--){
			Object[] where = (Object[])list.get(i);
			String condition = String.valueOf(where[0]);
			String filed = String.valueOf(where[1]);
			
			if("eq".equals(condition)){
				if(le == null){
					if(se1 == null)
						se1 = Restrictions.eq(filed, where[2]);
					else if(se2 == null)
						se2 = Restrictions.eq(filed, where[2]);
				}else{
					se = Restrictions.eq(filed, where[2]);
				}
			}else if("like".equals(condition)){
				if(le == null){
					if(se1 == null)
						se1 = Restrictions.like(filed, "%" + where[2] + "%");
					else if(se2 == null)
						se2 = Restrictions.like(filed, "%" + where[2] + "%");
				}else{
					se = Restrictions.like(filed, "%" + where[2] + "%");
				}
			}else if("ne".equals(condition)){
				if(le == null){
					if(se1 == null)
						se1 = Restrictions.ne(filed, where[2]);
					else if(se2 == null)
						se2 = Restrictions.ne(filed, where[2]);
				}else{
					se = Restrictions.ne(filed, where[2]);
				}
			}
			
			if(le == null){
				if(se1 != null && se2 != null){
					le = Restrictions.or(se1,se2);
				}
			}else{
				le = Restrictions.or(se,le);
			}
		}
		
		return le;
	}
}